"""
链接安全检测API控制器
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, validator
from api.service.link_safety_service import get_link_safety_service
from api.controller.auth import get_current_user
from api.utils.response import success, fail
from api.utils.logger import get_logger

logger = get_logger("link_safety")
 
router = APIRouter()


class LinkCheckRequest(BaseModel):
    """链接检测请求"""
    url: str
    use_remote: bool = True  # 是否使用远程API检测
    
    @validator('url')
    def validate_url(cls, v):
        if not v or not v.strip():
            raise ValueError('URL不能为空')
        
        v = v.strip()
        
        # 基本URL格式检查
        if not (v.startswith('http://') or v.startswith('https://')):
            # 尝试添加协议
            v = 'http://' + v
        
        return v


class LinkCheckResponse(BaseModel):
    """链接检测响应"""
    status: str  # safe, suspicious, dangerous, error, unknown
    message: str
    level: str  # safe, info, warning, danger, error
    source: str  # local_rules, phishtank, combined, etc.
    details: dict = None


@router.post("/link-safety/check")
async def check_link_safety(
    request: LinkCheckRequest,
    current_user: dict = Depends(get_current_user)
):
    """
    检测链接安全性
    
    - **url**: 要检测的URL
    - **use_remote**: 是否使用远程API（PhishTank）进行检测，默认True
    """
    try:
        # current_user是User对象，需要访问属性而不是字典方法
        username = getattr(current_user, 'username', 'unknown')
        logger.info(f"用户 {username} 请求检测链接: {request.url}")
        
        # 获取链接安全检测服务
        service = get_link_safety_service()
        
        # 执行检测
        result = service.check_url(request.url, use_remote=request.use_remote)
        
        logger.info(f"链接检测完成: {request.url} -> {result['status']}")
        
        return success(data=result, msg="检测完成")
        
    except Exception as e:
        logger.error(f"链接安全检测失败: {e}", exc_info=True)
        return fail(msg=f"检测失败: {str(e)}")


@router.post("/link-safety/cache/clear")
async def clear_cache(
    current_user: dict = Depends(get_current_user)
):
    """
    清空链接检测缓存
    需要管理员权限
    """
    try:
        # 检查是否为管理员
        is_admin = getattr(current_user, 'is_admin', False)
        if not is_admin:
            return fail(msg="需要管理员权限")
        
        service = get_link_safety_service()
        service.clear_cache()
        
        username = getattr(current_user, 'username', 'unknown')
        logger.info(f"管理员 {username} 清空了链接检测缓存")
        
        return success(msg="缓存已清空")
        
    except Exception as e:
        logger.error(f"清空缓存失败: {e}", exc_info=True)
        return fail(msg=f"清空缓存失败: {str(e)}")


@router.get("/link-safety/cache/stats")
async def get_cache_stats(
    current_user: dict = Depends(get_current_user)
):
    """
    获取缓存统计信息
    需要管理员权限
    """
    try:
        # 检查是否为管理员
        is_admin = getattr(current_user, 'is_admin', False)
        if not is_admin:
            return fail(msg="需要管理员权限")
        
        service = get_link_safety_service()
        stats = service.get_cache_stats()
        
        return success(data=stats, msg="获取成功")
        
    except Exception as e:
        logger.error(f"获取缓存统计失败: {e}", exc_info=True)
        return fail(msg=f"获取缓存统计失败: {str(e)}")